/**
 * ...
 * @author Thot
 */

function Map()
{
}



	// private
	
	Map.prototype._renderer 		= null;
	Map.prototype._width			= 1;
	Map.prototype._height			= 1;
	Map.prototype.camera			= null;
	
	
	// public
	Map.prototype.init = function( p_camW, p_camH )
	{
		var camera = new Camera();		
		this.camera = camera;
		
		
		this._renderer = new Renderer2D();
		//render settings
		this._renderer.camera = camera;
		
		//camera
		camera.x = 0;
		camera.y = 0;
		camera.z = 0;
		camera.width = p_camW;
		camera.height = p_camH;
		camera.pivotX = p_camW * 0.5;
		camera.pivotY = p_camH * 0.5;
		camera.pivotZ = 0;
	};
	
	Map.prototype.addLayer = function( p_layerId )
	{
		var canvas = document.createElement("canvas");
		var layer = new Layer();
		
		canvas.width = this.camera.width;
		canvas.height = this.camera.height;
		
		layer.name = p_layerId;
		layer.displayList = new DisplayList();
		layer.canvas = canvas;
		layer.context = layer.canvas.getContext("2d");
		//layer1.lazy = true;
		
		//boost displayList
		
		var boost = new SimpleCulling();
		boost.init();
		layer.displayList.boost = boost;
		layer.sorted = false;
		
		this._renderer.layers.push( layer );
		
		return layer;
	};
	
	Map.prototype.removeLayer = function( p_layerId )
	{
		var layer = this.getLayer( p_layerId );
		
		if( layer == null )
		{
			return null;
		}
			
		var index = this._renderer.layers.indexOf( layer );
		this._renderer.layers.splice( index, 1 );
		return layer;
	};
	
	Map.prototype.getLayer = function( p_layerId )
	{
		var tab = this._renderer.layers;
		var max = tab.length;
		var i = 0;
		var layer = null;
		
		for( i = 0; i < max; i++ )
		{
			layer = tab[i];
			
			if( layer.name == p_layerId )
				return layer;
		}
		
		return null;
	};
	
	Map.prototype.removeSprite = function( p_spr )
	{
		if( p_spr.displayList )
		{
			p_spr.displayList.removeChild( p_spr );
			p_spr.displayList = null;
		}
	};
	
	Map.prototype.addSpriteAt = function( p_spr, p_layerId, p_x, p_y )
	{
		var layer = this.getLayer( p_layerId );
		
		if( layer == null )
		{
			return;
		}
		
		p_spr.x = p_x;
		p_spr.y = p_y;
		
		layer.displayList.addChild( p_spr );
		p_spr.transformGroup = this.camera.transformGroup;
	};
	
	Map.prototype.getSpriteAt = function( p_layerId, p_x, p_y )
	{
		var layer = this.getLayer( p_layerId );
		var spr = null;
		
		if( layer != null )
		{
			spr = layer.displayList.getVisibleChildrenIn( p_x, p_y, 1, 1 )[0];
		}
		
		return spr;
	};
	
	Map.prototype.getLayers = function()
	{
		return this._renderer.layers;
	};

	
	// rendering loop
	Map.prototype.render = function()
	{
		this._renderer.render();
	};
		
	Map.prototype.clean = function()
	{
		this._renderer.layers = new Array();
	};
	
	
